package com.hgb.mall.admin.services.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.BCrypt;
import cn.hutool.json.JSONUtil;
import com.github.pagehelper.PageHelper;
import com.hgb.mall.admin.dao.UmsAdminRoleRelationDao;
import com.hgb.mall.admin.dto.UmsAdminParam;
import com.hgb.mall.admin.dto.UpdateAdminPasswordParam;
import com.hgb.mall.admin.services.AuthService;
import com.hgb.mall.admin.services.UmsAdminCacheService;
import com.hgb.mall.admin.services.UmsAdminService;
import com.hgb.mall.common.api.CommonResult;
import com.hgb.mall.common.api.ResultCode;
import com.hgb.mall.common.constant.AuthConstant;
import com.hgb.mall.common.domain.UserDto;
import com.hgb.mall.common.exception.Asserts;
import com.hgb.mall.mbg.entity.*;
import com.hgb.mall.mbg.mapper.*;
import org.mybatis.dynamic.sql.SqlBuilder;
import org.mybatis.dynamic.sql.render.RenderingStrategies;
import org.mybatis.dynamic.sql.select.render.SelectStatementProvider;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

import static org.mybatis.dynamic.sql.SqlBuilder.*;

/**
 * @Author: guibo
 * @Description:
 * @Date: Created in 0:40 2021/1/13
 * @Modified By:
 */
@Service
public class UmsAdminServiceImpl implements UmsAdminService {

    @Autowired
    private UmsAdminMapper adminMapper;
    @Autowired
    private UmsAdminRoleRelationMapper adminRoleRelationMapper;
    @Autowired
    private UmsAdminRoleRelationDao adminRoleRelationDao;
    @Autowired
    private UmsAdminLoginLogMapper loginLogMapper;
    @Autowired
    private AuthService authService;
    @Autowired
    private UmsAdminCacheService adminCacheService;
    @Autowired
    private HttpServletRequest request;

    /**
     * 根据用户名获取后台管理员
     *
     * @param username
     */
    @Override
    public UmsAdmin getAdminByUsername(String username) {
        Optional<UmsAdmin> adminList = adminMapper.selectOne(c -> c.where(
                UmsAdminDynamicSqlSupport.username, isEqualTo(username)));
        return adminList.orElse(null);
    }

    /**
     * 注册功能
     *
     * @param umsAdminParam
     */
    @Override
    public UmsAdmin register(UmsAdminParam umsAdminParam) {
        UmsAdmin umsAdmin = new UmsAdmin();
        BeanUtils.copyProperties(umsAdminParam, umsAdmin);
        umsAdmin.setCreateTime(new Date());
        umsAdmin.setStatus(1);
        //查询是否有相同用户名的用户

        Optional<UmsAdmin> umsAdminOptional = adminMapper.selectOne(c -> c.where(
                UmsAdminDynamicSqlSupport.username, isEqualTo(umsAdmin.getUsername())));
        if (umsAdminOptional.isPresent()) {
            return null;
        }
        //将密码进行加密操作
        String encodePassword = BCrypt.hashpw(umsAdmin.getPassword());
        umsAdmin.setPassword(encodePassword);
        adminMapper.insert(umsAdmin);
        return umsAdmin;


    }

    /**
     * 登录功能
     *
     * @param username 用户名
     * @param password 密码
     * @return 调用认证中心返回结果
     */
    @Override
    public CommonResult<Object> login(String username, String password) {
        if (StrUtil.isEmpty(username) || StrUtil.isEmpty(password)) {
            Asserts.fail("用户名或密码不能为空！");
        }
        Map<String, String> params = new HashMap<>();
        params.put("client_id", AuthConstant.ADMIN_CLIENT_ID);
        params.put("client_secret", "123456");
        params.put("grant_type", "password");
        params.put("username", username);
        params.put("password", password);
        CommonResult restResult = authService.getAccessToken(params);
        if (ResultCode.SUCCESS.getCode() == restResult.getCode() && restResult.getData() != null) {
            insertLoginLog(username);
        }
        return restResult;
    }

    /**
     * 根据用户id获取用户
     *
     * @param id
     */
    @Override
    public UmsAdmin getItem(Long id) {
        return adminMapper.selectByPrimaryKey(id).orElse(null);
    }

    /**
     * 根据用户名或昵称分页查询用户
     *
     * @param keyword
     * @param pageSize
     * @param pageNum
     */
    @Override
    public List<UmsAdmin> list(String keyword, Integer pageSize, Integer pageNum) {
        PageHelper.startPage(pageNum, pageSize);
        return adminMapper.select(c -> c.where(
                UmsAdminDynamicSqlSupport.username, isLikeWhenPresent(keyword).then(s -> "%" + s + "%")).or(
                UmsAdminDynamicSqlSupport.nickName, isLikeWhenPresent(keyword).then(s -> "%" + s + "%")));
    }

    /**
     * 修改指定用户信息
     *
     * @param id
     * @param admin
     */
    @Override
    public int update(Long id, UmsAdmin admin) {
        admin.setId(id);
        Optional<UmsAdmin> umsAdminOptional = adminMapper.selectByPrimaryKey(id);
        if (umsAdminOptional.isPresent()) {
            if (umsAdminOptional.get().getPassword().equals(admin.getPassword())) {
                //与原加密密码相同的不需要修改
                admin.setPassword(null);
            } else {
                //与原加密密码不同的需要加密修改
                if (StrUtil.isEmpty(admin.getPassword())) {
                    admin.setPassword(null);
                } else {
                    admin.setPassword(BCrypt.hashpw(admin.getPassword()));
                }
            }
        }
        int count = adminMapper.updateByPrimaryKeySelective(admin);
        adminCacheService.delAdmin(id);
        return count;
    }

    /**
     * 删除指定用户
     *
     * @param id
     */
    @Override
    public int delete(Long id) {
        int count = adminMapper.deleteByPrimaryKey(id);
        adminCacheService.delAdmin(id);
        return count;
    }

    @Override
    public int updateRole(Long adminId, List<Long> roleIds) {
        int count = roleIds == null ? 0 : roleIds.size();
        //先删除原来的关系

        adminRoleRelationMapper.delete(c -> c.where(UmsAdminRoleRelationDynamicSqlSupport.adminId, isEqualTo(adminId)));
        //建立新关系
        if (!CollectionUtils.isEmpty(roleIds)) {
            List<UmsAdminRoleRelation> list = new ArrayList<>();
            for (Long roleId : roleIds) {
                UmsAdminRoleRelation roleRelation = new UmsAdminRoleRelation();
                roleRelation.setAdminId(adminId);
                roleRelation.setRoleId(roleId);
                list.add(roleRelation);
            }
            adminRoleRelationDao.insertList(list);
        }
        return count;
    }

    @Override
    public List<UmsRole> getRoleList(Long adminId) {
        SelectStatementProvider selectStatement = SqlBuilder
                .select(UmsRoleDynamicSqlSupport.id.as("id"),
                        UmsRoleDynamicSqlSupport.name.as("name"),
                        UmsRoleDynamicSqlSupport.description.as("description"),
                        UmsRoleDynamicSqlSupport.adminCount.as("adminCount"),
                        UmsRoleDynamicSqlSupport.createTime.as("createTime"),
                        UmsRoleDynamicSqlSupport.status.as("status"),
                        UmsRoleDynamicSqlSupport.sort.as("sort"))
                .from(UmsAdminRoleRelationDynamicSqlSupport.umsAdminRoleRelation)
                .leftJoin(UmsRoleDynamicSqlSupport.umsRole)
                .on(UmsAdminRoleRelationDynamicSqlSupport.roleId, equalTo(UmsRoleDynamicSqlSupport.id))
                .where(UmsAdminRoleRelationDynamicSqlSupport.adminId, isEqualTo(adminId)).build()
                .render(RenderingStrategies.MYBATIS3);
        return adminRoleRelationDao.getRoleList(selectStatement);
    }

    @Override
    public List<UmsResource> getResourceList(Long adminId) {
        return adminRoleRelationDao.getResourceList(adminId);
    }

    @Override
    public int updatePassword(UpdateAdminPasswordParam param) {
        if (StrUtil.isEmpty(param.getUsername())
                || StrUtil.isEmpty(param.getOldPassword())
                || StrUtil.isEmpty(param.getNewPassword())) {
            return -1;
        }
        List<UmsAdmin> adminList = adminMapper
                .select(c -> c.where(UmsAdminDynamicSqlSupport.username, isEqualTo(param.getUsername())));
        if (CollUtil.isEmpty(adminList)) {
            return -2;
        }
        UmsAdmin umsAdmin = adminList.get(0);
        if (!BCrypt.checkpw(param.getOldPassword(), umsAdmin.getPassword())) {
            return -3;
        }
        umsAdmin.setPassword(BCrypt.hashpw(param.getNewPassword()));
        adminMapper.updateByPrimaryKey(umsAdmin);
        adminCacheService.delAdmin(umsAdmin.getId());
        return 1;
    }

    @Override
    public UserDto loadUserByUsername(String username) {
        //获取用户信息
        UmsAdmin admin = getAdminByUsername(username);
        if (admin != null) {
            List<UmsRole> roleList = getRoleList(admin.getId());
            UserDto userDTO = new UserDto();
            BeanUtils.copyProperties(admin, userDTO);
            if (CollUtil.isNotEmpty(roleList)) {
                List<String> roleStrList = roleList.stream().map(item -> item.getId() + "_" + item.getName())
                                                   .collect(Collectors.toList());
                userDTO.setRoles(roleStrList);
            }
            return userDTO;
        }
        return null;
    }

    @Override
    public UmsAdmin getCurrentAdmin() {
        String userStr = request.getHeader(AuthConstant.USER_TOKEN_HEADER);
        if (StrUtil.isEmpty(userStr)) {
            Asserts.fail(ResultCode.UNAUTHORIZED);
        }
        UserDto userDto = JSONUtil.toBean(userStr, UserDto.class);
        UmsAdmin admin = adminCacheService.getAdmin(userDto.getId());
        if (admin == null) {
            admin = adminMapper.selectByPrimaryKey(userDto.getId()).orElse(null);
            adminCacheService.setAdmin(admin);
        }
        return admin;
    }

    /**
     * 添加登录记录
     *
     * @param username 用户名
     */
    private void insertLoginLog(String username) {
        UmsAdmin admin = getAdminByUsername(username);
        if (admin == null) {
            return;
        }
        UmsAdminLoginLog loginLog = new UmsAdminLoginLog();
        loginLog.setAdminId(admin.getId());
        loginLog.setCreateTime(new Date());
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert attributes != null;
        HttpServletRequest request = attributes.getRequest();
        loginLog.setIp(request.getRemoteAddr());
        loginLogMapper.insert(loginLog);
    }
}
